package com.smartsystem.common.utils;

import com.smartsystem.modules.system.entity.SysUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户上下文工具类
 * 用于获取当前登录用户信息
 */
@Slf4j
public class UserContext {
    
    /**
     * 获取当前请求
     */
    private static HttpServletRequest getCurrentRequest() {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        return attributes != null ? attributes.getRequest() : null;
    }
    
    /**
     * 从请求头中获取Token
     */
    public static String getTokenFromRequest() {
        HttpServletRequest request = getCurrentRequest();
        if (request == null) {
            return null;
        }
        
        String authHeader = request.getHeader("Authorization");
        if (authHeader != null && authHeader.startsWith("Bearer ")) {
            return authHeader.substring(7);
        }
        return null;
    }
    
    /**
     * 获取当前登录用户ID
     */
    public static Long getCurrentUserId() {
        String token = getTokenFromRequest();
        if (token == null) {
            return null;
        }
        
        try {
            return JWTUtils.getUserIdFromToken(token);
        } catch (Exception e) {
            log.error("UserContext - Token解析失败: {}", e.getMessage());
            return null;
        }
    }
    
    /**
     * 获取当前登录用户名
     */
    public static String getCurrentUsername() {
        // 优先从Spring Security上下文获取
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated() 
            && !"anonymousUser".equals(authentication.getName())) {
            return authentication.getName();
        }
        
        // 从Token获取
        String token = getTokenFromRequest();
        if (token == null) {
            return null;
        }
        
        try {
            return JWTUtils.getUsernameFromToken(token);
        } catch (Exception e) {
            return null;
        }
    }
    
    /**
     * 验证当前Token是否有效
     */
    public static boolean isCurrentTokenValid() {
        String token = getTokenFromRequest();
        if (token == null) {
            return false;
        }
        
        try {
            return JWTUtils.validateToken(token);
        } catch (Exception e) {
            return false;
        }
    }
}